﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Rem.Objects;
using Rem.Objects.Forms;
using FileDB;
using System.Configuration;
using Rem.Objects.Forms.General;

namespace Rem.Explorer
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            this.Text = "管理工具";
            string databaseDir = AppDomain.CurrentDomain.BaseDirectory;
            AppDomain.CurrentDomain.SetData("DataDirectory", databaseDir);
            DataManager.Initiaze();
            //todo:
            Customer c = new Customer() { Name = ConfigurationManager.AppSettings[Customer.SelfCompany] };
            Customer.PrepareData(c);
        }

        #region menu handler
        private TreeNode GetTargetNode(RemTreeNode newNode, TreeView tree)
        {

            TreeNode result = null;
            foreach (TreeNode item in tree.Nodes)
            {
                result = GetTargetNode(newNode, item);
                if (result != null)
                {
                    return result;
                }
            }
            return result;
        }
        private TreeNode GetTargetNode(RemTreeNode newNode, TreeNode rootNode)
        {
            TreeNode targetNode = null;
            foreach (TreeNode item in rootNode.Nodes)
            {
                if (item is RemTreeNode)
                {
                    if ((item as RemTreeNode).BaseType == newNode.BaseType &&
                        (item as RemTreeNode).NodeType == this.nodeDockMap[newNode.BaseType])
                    {
                        targetNode = item;
                        return targetNode;
                    }
                    else if (item.Nodes.Count > 0)
                    {
                        targetNode = GetTargetNode(newNode, item);
                        if (targetNode != null)
                        {
                            return targetNode;
                        }
                    }
                }
            }
            return targetNode;
        }
        #endregion

        Dictionary<Form, RemTreeNode> nodes = new Dictionary<Form, RemTreeNode>();
        Dictionary<BaseObjectTypes, MenuNodeType> nodeDockMap = new Dictionary<BaseObjectTypes, MenuNodeType>();

        private void MainForm_Load(object sender, EventArgs e)
        {
            // todo splash screen
            Application.DoEvents();
            // check database and network
            // initialize nodes
            InitializeData();
            InitializeTab();
            InitializeTree();
            InitToolbars();

            InitializeEventHandler();
            InitializeMonitor();
            this.workspaceTree.ExpandAll();
            InitializeStartPage();

            LoginForm form = new LoginForm()
            {
                ExpectedPassword = ConfigurationManager.AppSettings["password"],
                StartPosition = FormStartPosition.CenterScreen
            };
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.No)
            {
                this.Close();
            }
            else
            {
                NotHandled(null, null);
            }

        }
        #region initialization
        private void InitializeData()
        {
            //BaseForm.RemDatabaseEntities = new RemDatabaseEntities();
        }

        private void InitializeEventHandler()
        {
            BaseForm.Forms.FormAdded += HandleNewForm;
            BaseForm.Forms.FormRemoved += HandleRemoveForm;
            BaseForm.FormTitleChanged += HandleTitleChanged;
        }

        private void InitializeTab()
        {
            this.tabPage1.Text = "工作区间";
            //this.TabControl1.TabPages.Add("收藏夹子");
        }

        void InitializeTree()
        {

            workspaceTree.HideSelection = false;
            workspaceTree.HotTracking = true;
            workspaceTree.Dock = DockStyle.Fill;
            workspaceTree.Scrollable = true;
            this.nodeDockMap.Add(BaseObjectTypes.Employee, MenuNodeType.Employees);
            this.nodeDockMap.Add(BaseObjectTypes.Contract, MenuNodeType.Contracts);
            this.nodeDockMap.Add(BaseObjectTypes.EmployeeQuery, MenuNodeType.QueryEntry);
            this.nodeDockMap.Add(BaseObjectTypes.CustomerQuery, MenuNodeType.QueryEntry);
            this.nodeDockMap.Add(BaseObjectTypes.ContractQuery, MenuNodeType.QueryEntry);
            this.nodeDockMap.Add(BaseObjectTypes.ReminderQuery, MenuNodeType.QueryEntry);
            this.nodeDockMap.Add(BaseObjectTypes.Reminder, MenuNodeType.Reminds);
            this.nodeDockMap.Add(BaseObjectTypes.Customer, MenuNodeType.Customers);
            //this.nodeDockMap.Add(BaseObjectTypes.Employee, MenuNodeType.Employees);

            this.workspaceTree.Nodes.AddRange(
                new TreeNode[]{
                    new RemTreeNode("基本信息", 0,0,
                      new TreeNode[]{ 
                         // new RemTreeNode("员工", 0, 0){ BaseType = BaseObjectTypes.Employee, NodeType = MenuNodeType.Employees},
                          new RemTreeNode("合同", 0, 0){ BaseType = BaseObjectTypes.Contract, NodeType= MenuNodeType.Contracts},
                          new RemTreeNode("提醒", 0, 0){ BaseType = BaseObjectTypes.Reminder, NodeType = MenuNodeType.Reminds},
                          new RemTreeNode("客户", 0, 0){ BaseType = BaseObjectTypes.Customer, NodeType = MenuNodeType.Customers},
                      }){ NodeType = MenuNodeType.BasicInfo },
                    new RemTreeNode("应用", 0,0,
                      new TreeNode[]{ 
                          //new RemTreeNode("查询", 0, 0){ BaseType = BaseObjectTypes.Queries, NodeType= MenuNodeType.QueryEntry},
                         // new RemTreeNode("员工查询", 0, 0){ BaseType = BaseObjectTypes.EmployeeQuery, NodeType = MenuNodeType.QueryEntry},
                          new RemTreeNode("合同查询", 0, 0){ BaseType = BaseObjectTypes.ContractQuery, NodeType = MenuNodeType.QueryEntry},
                          new RemTreeNode("提醒查询", 0, 0){ BaseType = BaseObjectTypes.ReminderQuery, NodeType = MenuNodeType.QueryEntry},
                          new RemTreeNode("客户查询", 0, 0){ BaseType = BaseObjectTypes.CustomerQuery, NodeType = MenuNodeType.QueryEntry},
                      }) { NodeType = MenuNodeType.Application },
                }
                );

        }
        #endregion

        #region envent handler
        private void HandleNewForm(Form f)
        {
            f.MdiParent = this;

            //Cursor.Current = Cursors.Default;
            RemTreeNode newNode = new RemTreeNode()
            {
                Text = f.Text,
                Form = f,
                NodeType = MenuNodeType.ExistingWindow,
                BaseType = (f as BaseForm).BaseType
            };

            //todo targetnode is
            TreeNode targetNode = GetTargetNode(newNode, this.workspaceTree);

            //this.workspaceTree.SelectedNode.Nodes.Add(newNode);
            if (targetNode != null)
            {
                targetNode.Nodes.Add(newNode);
            }
            else
            {
                //todo: debug handle error
                MessageBox.Show("没有对应的节点");
            }
            nodes.Add(f, newNode);
            this.workspaceTree.SelectedNode = newNode;
            newNode.Parent.Expand();
        }

        public void HandleRemoveForm(Form f)
        {
            this.workspaceTree.Nodes.Remove(nodes[f]);
            nodes.Remove(f);
        }


        private void HandleTitleChanged(Form f)
        {
            nodes[f].Text = f.Text;
        }

        private void InitializeMonitor()
        {
            // add thread timer to check reminder and prompt reminder

        }

        private void InitToolbars()
        {
            // todo
        }

        private void InitializeStartPage()
        {
        }
        #endregion

        private void workspaceTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (this.workspaceTree.SelectedNode != null)
            {
                RemTreeNode selectedNode = this.workspaceTree.SelectedNode as RemTreeNode;
                if (selectedNode != null && selectedNode.Form != null)
                {
                    if (selectedNode.Form.WindowState == FormWindowState.Minimized)
                    {
                        selectedNode.Form.WindowState = FormWindowState.Normal;
                    }
                    selectedNode.Form.Show();
                    selectedNode.Form.Focus();
                    selectedNode.Form.Activate();
                }
            }
        }

        private void workspaceTree_MouseUp(object sender, MouseEventArgs e)
        {
            RemTreeNode tempNode = null;
            if (e.Button == MouseButtons.Right)
            {
                tempNode = workspaceTree.GetNodeAt(e.X, e.Y) as RemTreeNode;
                if (tempNode != null)
                {
                    tempNode.ShowContextMenu(e.X, e.Y);
                    workspaceTree.SelectedNode = tempNode;
                }
            }
        }
        #region menu actions
        private void newEmployeeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormHelper.OpenObjectForm(BaseObjectTypes.Employee, null, false);
        }

        private void allEmployeeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormHelper.OpenObjectForm(BaseObjectTypes.EmployeeQuery, null, false);
        }

        private void 所有合同ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //FormHelper.OpenObjectForm(BaseObjectTypes.ContractQuery, null, false);
            QueryForm.OpenContractQuery(10);
        }

        private void 添加合同ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormHelper.OpenObjectForm(BaseObjectTypes.Contract, null, false);
        }

        private void 本月合同ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QueryForm.OpenContractQuery(1);
        }

        private void 所有客户ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //FormHelper.OpenObjectForm(BaseObjectTypes.CustomerQuery, null, false);
            QueryForm.OpenCustomerQuery(1);
        }

        private void OpenCustomerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GoToForm.OpenForm("Id", "Name", BaseObjectTypes.Customer);
        }

        private void 添加客户ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormHelper.OpenObjectForm(BaseObjectTypes.Customer, null, false);
        }

        private void currentDayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QueryForm.OpenReminderQuery(1);
        }

        private void thisMonthToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QueryForm.OpenReminderQuery(5);
        }

        private void contractToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QueryForm.OpenReminderQuery(4);
        }

        private void 重要ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QueryForm.OpenReminderQuery(7);
        }

        private void 生日提醒ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QueryForm.OpenReminderQuery(8);
        }

        private void 所有提醒ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QueryForm.OpenReminderQuery(9);
            //FormHelper.OpenObjectForm(BaseObjectTypes.ReminderQuery, null, false);
        }

        private void NotHandled(object sender, EventArgs e)
        {
            QueryForm.OpenReminderQuery(3);
        }

        private void 上月合同ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QueryForm.OpenContractQuery(2);
        }

        private void 本年合同ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QueryForm.OpenContractQuery(3);
        }
        private void 添加周期提醒ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReminderForm2.NewPeriodRemind();
        }

        private void 添加提醒ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormHelper.OpenObjectForm(BaseObjectTypes.Reminder, null, false);
        }
        #endregion

        private void 合同统计ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                ContractStaticsInfo info = new ContractStaticsInfo()
                {
                    Text = "本月合同统计信息"
                };
                info.Dock = DockStyle.Fill;
                info.Show();
            }
            finally
            {
                this.Cursor = Cursors.Default;

            }
        }

        private void 本公司信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CustomerForm f = new CustomerForm(Customer.GetSelfCompany());
            f.Show();
            f.Dock = DockStyle.Fill;
        }

        private void 锁定ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoginForm form = new LoginForm()
            {
                ExpectedPassword = ConfigurationManager.AppSettings["password"]

            };
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.No)
            {
                this.Close();
            }
        }
        private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpdatePassword updatefrom = new UpdatePassword();
            updatefrom.Expectedpasswordstr = ConfigurationManager.AppSettings["password"];
            if (updatefrom.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ConfigurationManager.RefreshSection("appSettings");
            }
        }
    }
}
